package com.example.lenovo.manager;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVCloudQueryResult;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVOSCloud;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.CloudQueryCallback;
import com.avos.avoscloud.FindCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class Manager extends Fragment {

    private ListView listView;
    private List<Map<String,Object>> list = new ArrayList<>();
    private List<AVObject> mData = new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_manager, container, false);

        System.out.println("00");

        System.out.println("01");
        listView = (ListView) view.findViewById(R.id.Manager);

        System.out.println("02");
        AVOSCloud.initialize(getActivity(), "Po6OudEc9QxRgv1qcussxBxi-gzGzoHsz", "EFNsW7y5aXtKMkpU50xyhHNk");
        final AVQuery<AVObject> query = new AVQuery<>("ManagerUser");
        query.whereEqualTo("Sure",0);
        query.findInBackground(new FindCallback<AVObject>() {


            @Override
            public void done(final List<AVObject> listr, AVException e) {
                final List<AVObject> priorityEqualsZeroTodos = listr;
                mData = listr;
                for(int i = 0;i<priorityEqualsZeroTodos.size();i++){
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("UserName", priorityEqualsZeroTodos.get(i).getString("UserName"));
                    System.out.println("Name：" + priorityEqualsZeroTodos.get(i).getString("UserName"));
                    map.put("RealName", priorityEqualsZeroTodos.get(i).getString("RealName"));
                    list.add(map);
                    System.out.println(priorityEqualsZeroTodos.get(i).toJSONObject().toString());
                    System.out.println(map.toString());
                }
                String[] from = {"UserName","RealName"};
                int[] to = {R.id.UserNameTable,R.id.RealNameTable};
                MyAdapter simpleAdapter = new MyAdapter(getActivity(),list,R.layout.listview_item,from,to);
                listView.setAdapter(simpleAdapter);
                listView.setOnItemClickListener(
                        new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                Toast.makeText(getActivity(), "This is " + position + " 行！", Toast.LENGTH_LONG).show();
                            }
                        }
                );
                setListViewHeightBasedOnChildren(listView);
            }
        });

        return view;
    }

    public void showInfoOne(final int position, final List<AVObject> IdList){

        ImageView img=new ImageView(getActivity());
        final int i = -1;
        /*img.setImageResource(R.drawable.b);*/
        new AlertDialog.Builder(getActivity())
                .setTitle("确认拒绝吗？")
                .setMessage("用户名:"+IdList.get(position).getString("UserName")+"\n真实姓名："+IdList.get(position).getString("RealName")+"\n手机号:"+IdList.get(position).getString("Mobile"))
                .setPositiveButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        AVQuery.doCloudQueryInBackground("update ManagerUser set Sure="+ i +" where objectId='"+ IdList.get(position).getObjectId() +"'", new CloudQueryCallback<AVCloudQueryResult>() {
                            @Override
                            public void done(AVCloudQueryResult avCloudQueryResult, AVException e) {
                                // 如果 e 为空，说明保存成功
                            }
                        });
                    }
                })
                .show();
    }

    public void showInfoTwo(final int position, final List<AVObject> IdList){

        ImageView img=new ImageView(getActivity());
        final int i = 1;
        /*img.setImageResource(R.drawable.b);*/
        new AlertDialog.Builder(getActivity())
                .setTitle("确认拒绝吗？")
                .setMessage("用户名"+IdList.get(position).getString("UserName")+"\n真实姓名："+IdList.get(position).getString("RealName")+"\n手机号:"+IdList.get(position).getString("Mobile"))
                .setPositiveButton("通过", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        AVQuery.doCloudQueryInBackground("update ManagerUser set Sure=" + i + " where objectId='" + IdList.get(position).getObjectId() + "'", new CloudQueryCallback<AVCloudQueryResult>() {
                            @Override
                            public void done(AVCloudQueryResult avCloudQueryResult, AVException e) {
                                // 如果 e 为空，说明保存成功
                            }
                        });
                    }
                })
                .show();
    }

    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) { // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0); // 计算子项View 的宽高
            totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

    /**
     * 重写的数据适配器
     */
    class MyAdapter extends SimpleAdapter {

        LayoutInflater inflater;

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            final Holder holder;
            final int num=position;
            if(convertView!=null){
                holder=(Holder) convertView.getTag();
            }else {
                holder=new Holder();
                convertView=inflater.inflate(R.layout.listview_manager, null);
                holder.UserName = (TextView) convertView.findViewById(R.id.UserNameTable);
                holder.RealName = (TextView) convertView.findViewById(R.id.RealNameTable);
                holder.RefuseButton = (Button) convertView.findViewById(R.id.RefuseTable);
                holder.AllowButton = (Button) convertView.findViewById(R.id.AllowTable);
                convertView.setTag(holder);
            }


            for(int i = 0;i<mData.size();i++){
                holder.UserName.setText(mData.get(i).getString("UserName"));
                holder.RealName.setText(mData.get(i).getString("RealName"));

            }

            View.OnClickListener listenerone=new View.OnClickListener(){
                @Override
                public void onClick(View v)
                {
                    showInfoOne(position, mData);
                }
            };
            holder.RefuseButton.setOnClickListener(listenerone);

            View.OnClickListener listenertwo=new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showInfoTwo(position, mData);
                }
            };
            holder.AllowButton.setOnClickListener(listenertwo);





            return super.getView(position, convertView, parent);
        }

        public MyAdapter(Context context, List<? extends Map<String, ?>> data,
                         int resource, String[] from, int[] to) {
            super(context, data, resource, from, to);
//          this.context=context;
            inflater=LayoutInflater.from(context);
            // TODO Auto-generated constructor stub
        }
    }

    class Holder{
        public TextView UserName,RealName;
        public Button RefuseButton,AllowButton;
    }

}
